package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.constant.UserConstants;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.*;
import com.ruoyi.common.core.utils.bean.BeanValidators;
import com.ruoyi.common.core.utils.ip.IpUtils;
import com.ruoyi.common.datascope.annotation.DataScope;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.domain.SysRole;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.domain.WxUser;
import com.ruoyi.system.api.model.UserDto;
import com.ruoyi.system.api.model.UserInfoDto;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.dto.DriverInfo;
import com.ruoyi.system.domain.dto.IdCardInfo;
import com.ruoyi.system.domain.dto.LhsTricycle;
import com.ruoyi.system.domain.vo.SysUserVo;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.validation.Validator;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户 业务层处理
 *
 * @author ruoyi
 */
@Service
public class SysUserServiceImpl implements ISysUserService {
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private UserDeptRefMapper userDeptRefMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysPostMapper postMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private SysUserPostMapper userPostMapper;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    protected Validator validator;


    @Autowired
    private SysOrganizationDomainMapper sysOrganizationDomainMapper;

    /**
     * 通过openid查询用户
     *
     * @param openid 用户唯一标识
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByOpenid(String openid) {
        SysUser user1 = userMapper.selectUserByOpenid(openid);
        if (null == user1) {
            String name = "微信用户";
            user1 = new SysUser();
            user1.setUserName(name);
            user1.setOpenId(openid);
            user1.setNickName(name);
            user1.setDelFlag("0");
            int count = userMapper.insert(user1);
            if (1 > count) {
                throw new ServiceException("数据操作失败");
            }
        }
        return user1;
    }

    @Override
    public WxUser getInfoByPhone(String phone, String identity) {
        if ("customer".equalsIgnoreCase(identity)) {
            WxUser customer = userMapper.getInfoByPhone(phone);
            if (customer == null) {
                return null;
            }
            if (customer != null && StringUtils.isNotEmpty(customer.getDriverLicenseImg())) {
                customer.setRealName(true);
            } else {
                customer.setRealName(false);
            }
            return customer;
        } else if ("driver".equalsIgnoreCase(identity)) {
            WxUser infoByPhone = userMapper.getInfoByPhoneDriver(phone);
            if (infoByPhone == null) {
                return null;
            }
            if (infoByPhone != null && StringUtils.isNotEmpty(infoByPhone.getDriverLicenseImg())) {
                infoByPhone.setRealName(true);
            } else {
                infoByPhone.setRealName(false);
            }
            return infoByPhone;
        } else if ("merchant".equalsIgnoreCase(identity)) {
            WxUser infoByPhone = userMapper.getLhsTricycleInfoByPhone(phone);
            if (infoByPhone == null) {
                return null;
            }
            if (infoByPhone != null && StringUtils.isNotEmpty(infoByPhone.getDriverLicenseImg())) {
                infoByPhone.setRealName(true);
            } else {
                infoByPhone.setRealName(false);
            }
            return infoByPhone;
        } else {
            WxUser wxUser = userMapper.getBusinessUserInfoByPhone(phone);
            if (wxUser == null) {
                return null;
            }
            if (StringUtils.isNotEmpty(wxUser.getIdCard())) {
                wxUser.setRealName(true);
            } else {
                wxUser.setRealName(false);
            }

            wxUser.setName(wxUser.getNickName());
            return wxUser;
        }
    }

    /**
     * 新增微信用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int insertWxUser(SysUser user) {
        // 新增用户信息
        String ip = IpUtils.getIpAddr();
        user.setLoginIp(ip);
        user.setCreateTime(DateUtils.getCurrentTime());
        if (StringUtils.isEmpty(user.getIdentity())) {
            user.setIdentity("driver");
        }
        user.setCreateBy("lvlianassistant");
        if ("student".equalsIgnoreCase(user.getIdentity())) {
            user.setCreateBy("weidianyuan");
        }
        if (StringUtils.isEmpty(user.getPhonenumber())) {
            return userMapper.insertUser(user);
        } else {
            SysUser infoByPhone = userMapper.selectUserByPhone(user.getPhonenumber());
            if (null == infoByPhone) {
                return userMapper.insertUser(user);
            } else {
                return userMapper.updateUser(user);
            }
        }
    }

    /**
     * 根据条件分页查询用户列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUserList(SysUser user) {
        List<SysUser> users = userMapper.selectUserList(user);
        return users;
    }

    /**
     * 根据条件分页查询已分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectAllocatedList(SysUser user) {
        return userMapper.selectAllocatedList(user);
    }

    /**
     * 根据条件分页查询未分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUnallocatedList(SysUser user) {
        return userMapper.selectUnallocatedList(user);
    }

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByUserName(String userName) {
        return userMapper.selectUserByUserName(userName);
    }

    /**
     * 通过用户ID查询用户
     *
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserById(Long userId) {
        return userMapper.selectById(userId);
    }

    /**
     * 查询用户所属角色组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(String userName) {
        List<SysRole> list = roleMapper.selectRolesByUserName(userName);
        if (CollectionUtils.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysRole::getRoleName).collect(Collectors.joining(","));
    }

    /**
     * 查询用户所属岗位组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserPostGroup(String userName) {
        List<SysPost> list = postMapper.selectPostsByUserName(userName);
        if (CollectionUtils.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysPost::getPostName).collect(Collectors.joining(","));
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean checkUserNameUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkUserNameUnique(user.getUserName());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验手机号码是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public boolean checkPhoneUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkPhoneUnique(user.getPhonenumber());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public boolean checkEmailUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkEmailUnique(user.getEmail());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户是否允许操作
     *
     * @param user 用户信息
     */
    @Override
    public void checkUserAllowed(SysUser user) {
        if (StringUtils.isNotNull(user.getUserId()) && user.isAdmin()) {
            throw new ServiceException("不允许操作超级管理员用户");
        }
    }

    /**
     * 校验用户是否有数据权限
     *
     * @param userId 用户id
     */
    @Override
    public void checkUserDataScope(Long userId) {
        if (!SysUser.isAdmin(SecurityUtils.getUserId())) {
            SysUser user = new SysUser();
            user.setUserId(userId);
            List<SysUser> users = SpringUtils.getAopProxy(this).selectUserList(user);
            if (StringUtils.isEmpty(users)) {
                throw new ServiceException("没有权限访问用户数据！");
            }
        }
    }

    /**
     * 新增保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertUser(SysUser user) {
        user.setCreateBy(SecurityUtils.getUsername());
        user.setCreateTime(DateUtils.getCurrentTime());

        user.setUpdateBy(SecurityUtils.getUsername());
        user.setUpdateTime(DateUtils.getCurrentTime());
        user.setDelFlag("0");
        SysUser userInfoExist = userMapper.findUserInfoExist(user);
        // 新增用户信息
        int count = 0;
        if (null == user.getUserId()) {
            if (null != userInfoExist) {
                throw new ServiceException("用户账号或手机号已经存在");
            }
            count = userMapper.insert(user);
        } else {
            if (null != userInfoExist && user.getUserId().equals(userInfoExist.getUserId())) {
                count = userMapper.updateById(user);
            } else {
                throw new ServiceException("用户账号或手机号已经存在");
            }
        }
        if (1 > count) {
            throw new ServiceException("数据操作失败");
        }
        // 新增用户岗位关联
        insertUserPost(user);
        // 新增用户与角色管理
        insertUserRole(user);
        //调整公司 ，一个用户存在多个公司
        if (user.getDeptIds() != null && user.getDeptIds().size() > 0) {
            List<UserDeptRef> list = new ArrayList<>();
            for (Long id : user.getDeptIds()) {
                UserDeptRef userDept = new UserDeptRef();
                userDept.setUserId(user.getUserId());
                userDept.setDeptId(id);
                userDept.setId(MD5Utils.md5(user.getUserId() + "" + id));
                list.add(userDept);
            }
            count = userDeptRefMapper.savebatchUserDept(list);
            if (1 > count) {
                throw new ServiceException("数据操作失败");
            }
        }
        return count;
    }

    /**
     * 注册用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean registerUser(SysUser user) {
        return userMapper.insertUser(user) > 0;
    }

    /**
     * 修改保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateUser(SysUser user) {
        Long userId = user.getUserId();
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 新增用户与角色管理
        insertUserRole(user);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPostByUserId(userId);
        // 新增用户与岗位管理
        insertUserPost(user);
        userDeptRefMapper.deleteDeptByUserId(userId);
        //     删除用户与公司关联
        if (user.getDeptIds() != null && user.getDeptIds().size() > 0) {
            List<UserDeptRef> list = new ArrayList<>();
//        调整公司 ，一个用户存在多个公司
            for (Long id : user.getDeptIds()) {
                UserDeptRef userDept = new UserDeptRef();
                userDept.setUserId(userId);
                userDept.setDeptId(id);
                userDept.setId(MD5Utils.md5(userId + "" + id));
                list.add(userDept);
            }
            int count = userDeptRefMapper.savebatchUserDept(list);
            if (1 > count) {
                throw new ServiceException("数据操作失败");
            }
        }
        return userMapper.updateUser(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateWxUser(WxUser wxUser) {
        if (StringUtils.isNotEmpty(wxUser.getName())) {
            wxUser.setUserName(wxUser.getName());
            wxUser.setNickName(wxUser.getName());
        }
        SysUser sysUser = new SysUser();
        IdCardInfo idCardInfo = new IdCardInfo();
        BeanUtils.copyProperties(wxUser, idCardInfo); // 注意参数顺序：目标在前，源在后
        idCardInfo.setIdCard(wxUser.getIdCard());
        if (StringUtils.isNotEmpty(idCardInfo.getIdCard())) {
            idCardInfo.setId(MD5Utils.md5(idCardInfo.getIdCard()));
            if (StringUtils.isEmpty(idCardInfo.getName())) {
                idCardInfo.setName(wxUser.getNickName());
            }

            idCardInfo.setCreateUser(SecurityUtils.getUsername());
            idCardInfo.setCreateDate(DateUtils.getCurrentTime());
            userMapper.insertIdCardInfo(idCardInfo);
        }


        if (StringUtils.isNotEmpty(wxUser.getIdCard())) {
            DriverInfo driverInfo = new DriverInfo();
            BeanUtils.copyProperties(wxUser, driverInfo);
            driverInfo.setLicenseNo(wxUser.getIdCard());
            driverInfo.setPhoneNo(wxUser.getPhoneNo());
            driverInfo.setCreateUser(SecurityUtils.getUsername());
            driverInfo.setCreateDate(DateUtils.getCurrentTime());
            driverInfo.setViewFlag(true);
            driverInfo.setDataSource("实时物流小程序");
            driverInfo.setDataStatus("待审批");
            driverInfo.setApprovedType(wxUser.getApprovedType());
            driverInfo.setId(MD5Utils.md5(driverInfo.getLicenseNo() + driverInfo.getPhoneNo() + driverInfo.getDataSource()));
            userMapper.insertDriverInfo(driverInfo);
        }

        if ("收回莱".equalsIgnoreCase(wxUser.getDataSource()) && StringUtils.isNotEmpty(wxUser.getIdCard())) {


            LhsTricycle driverInfo = new LhsTricycle();
            BeanUtils.copyProperties(wxUser, driverInfo);
            driverInfo.setLicenseNo(wxUser.getIdCard());
            driverInfo.setPhoneNo(wxUser.getPhoneNo());
            driverInfo.setCreateUser(SecurityUtils.getUsername());
            driverInfo.setCreateDate(DateUtils.getCurrentTime());
            driverInfo.setViewFlag(true);
            driverInfo.setDataSource("收回莱小程序");
            driverInfo.setDataStatus("待审批");
            driverInfo.setApprovedType(wxUser.getApprovedType());
            driverInfo.setId(MD5Utils.md5(driverInfo.getLicenseNo() + driverInfo.getPhoneNo() + driverInfo.getDataSource()));
            userMapper.insertLhsTricycle(driverInfo);
        }


        BeanUtils.copyProperties(wxUser, sysUser); // 注意参数顺序：目标在前，源在后
        sysUser.setAvatar(wxUser.getAvatarUrl());
        sysUser.setPhonenumber(wxUser.getPhone());
        return userMapper.updateUser(sysUser);
    }

    @Override
    public List<WxUser> queryWxUser(UserDto user) {
        List<WxUser> list = userMapper.queryWxUser(user);
        return list;
    }

    @Override
    public void unifiedName(WxUser wxUser) {

        try {
            if (wxUser != null && StringUtils.isNotEmpty(wxUser.getIdCard())) {
                if (StringUtils.isEmpty(wxUser.getName())) {
                    wxUser.setName(wxUser.getName());
                }
//同步名字

                int i = userMapper.unifiedSysUserName(wxUser);
                i = userMapper.unifiedDriverName(wxUser);
                userMapper.unifiedDriverNameByPhone(wxUser);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    @Override
    public WxUser getInfoByOpenId(String openId) {
        WxUser wxUser = userMapper.getInfoByOpenId(openId);
        return wxUser;
    }

    @Override
    public SysUser selectUserByPhone(String phonenumber) {
        return userMapper.selectUserByPhone(phonenumber);
    }

    @Override
    public int updateSysIdCardInfo(IdCardInfo idCardInfo) {
        int result = 0;
        if (StringUtils.isEmpty(idCardInfo.getId())) {

            idCardInfo.setId(MD5Utils.md5(idCardInfo.getIdCard()));
            idCardInfo.setCreateUser(SecurityUtils.getUsername());
            idCardInfo.setCreateDate(DateUtils.getCurrentTime());

            result = userMapper.insertIdCardInfo(idCardInfo);
        } else {
            result = userMapper.updateSysIdCardInfo(idCardInfo);
        }
        return result;
    }

    @Override
    public IdCardInfo querySysIdCardInfoById(String id) {
        IdCardInfo idCardInfo = userMapper.querySysIdCardInfoById(id);
        if (null == idCardInfo) {
            idCardInfo = userMapper.querySysIdCardInfoById2(id);
        }
        return idCardInfo;
    }

    @Override
    public List<UserDeptRef> selectDeptIdsByUserId(Long userId) {
        LambdaQueryWrapper<UserDeptRef> queryWrapper = new LambdaQueryWrapper<UserDeptRef>()
                .eq(UserDeptRef::getUserId, userId);
        return userDeptRefMapper.selectList(queryWrapper);
    }

    @Override
    public int updateSysUser(SysUser user) {
        Long userId = user.getUserId();
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        if (user.getUserId() != null) {
            // 新增用户与角色管理
            insertUserRole(user);
        }

        if (StringUtils.isNotEmpty(user.getName())) {
            user.setUserName(user.getName());
            user.setNickName(user.getName());
        }

        IdCardInfo idCardInfo = new IdCardInfo();
        BeanUtils.copyProperties(user, idCardInfo);
        int result = 0;
        if (StringUtils.isNotEmpty(idCardInfo.getIdCard())) {
//             如果存在 就不要增加了
            boolean exist = userMapper.findCardInfoExist(idCardInfo.getIdCard());
            idCardInfo.setId(MD5Utils.md5(idCardInfo.getIdCard()));
            if (StringUtils.isEmpty(idCardInfo.getName())) {
                idCardInfo.setName(user.getNickName());
            }
            idCardInfo.setCreateUser(SecurityUtils.getUsername());
            idCardInfo.setCreateDate(DateUtils.getCurrentTime());
            idCardInfo.setPhone(user.getPhonenumber());
            idCardInfo.setGender(IDCardValidator.getGenderFromIdCard(idCardInfo.getIdCard()));
            idCardInfo.setUserId(user.getUserId());
            if (exist) {
                result = userMapper.updateSysIdCardInfo(idCardInfo);
                result = userMapper.updateDriverName(idCardInfo);
            } else {
                result = userMapper.insertIdCardInfo(idCardInfo);
            }
        }


        SysUser sysUser = userMapper.selectUserByUserName(user.getUserName());
        if (sysUser == null) {
            result = this.insertUser(user);
        } else {
            user.setUserId(sysUser.getUserId());
            user.setIdCard(idCardInfo.getIdCard());
//            user.setUserName(idCardInfo.getName());
            user.setNickName(idCardInfo.getName());
            result = this.updateUser(user);
        }
        return result;
    }

    @Override
    public List<SysUserVo> queryUserInfo(UserDto user) {

        user.setCreateUser(SecurityUtils.getUsername());

//        TODO
        List<SysUserVo> users = userMapper.queryUserInfo(user);

        for (SysUserVo vo : users) {
            List<SysOrganizationDomainLabel> groupList = sysOrganizationDomainMapper.queryDomainListByRef(vo.getUserId() + "", "1");

            String labels = groupList.stream()
                    .map(SysOrganizationDomainLabel::getLabel) // 提取label属性
                    .collect(Collectors.joining(",")); // 以逗号分隔拼接字符串
            vo.setGroupLabel(labels);


            List<SysOrganizationDomainLabel> domainList = sysOrganizationDomainMapper.queryDomainListByRef(vo.getUserId() + "", "2");
            String domains = domainList.stream()
                    .map(SysOrganizationDomainLabel::getLabel) // 提取label属性
                    .collect(Collectors.joining(",")); // 以逗号分隔拼接字符串
            vo.setDomainLabel(domains);


            List<SysOrganizationDomainLabel> companyList = sysOrganizationDomainMapper.queryDomainListByRef(vo.getUserId() + "", "3");
            String companys = companyList.stream()
                    .map(SysOrganizationDomainLabel::getLabel) // 提取label属性
                    .collect(Collectors.joining(",")); // 以逗号分隔拼接字符串
            vo.setCompanyLabel(companys);

            List<SysOrganizationDomainLabel> accountList = sysOrganizationDomainMapper.queryDomainListByRef(vo.getUserId() + "", "4");
            String accounts = accountList.stream()
                    .map(SysOrganizationDomainLabel::getLabel) // 提取label属性
                    .collect(Collectors.joining(",")); // 以逗号分隔拼接字符串
            vo.setAccountLabel(accounts);
        }

        return users;
    }

    @Override
    public int updateUserInfo(List<UserInfoDto> dtoList) {

//        SysOrganizationDomain domain = sysOrganizationDomainMapper.selectSysOrganizationDomainById(domainRef.getDomainId());

        for (UserInfoDto po : dtoList) {
            userMapper.deleteUserOrganizationDomainByUserId(po.getUserId());
        }

        if (!dtoList.isEmpty()) {
            for (UserInfoDto po : dtoList) {
                po.setId(MD5Utils.md5(po.getUserId() + po.getDomainId()));
                po.setBoundary(po.getCategory());
            }
        }
//        先删除

//        再插入  选中二级  要把一级也插入 。。
        return userMapper.updateUserInfo(dtoList);
    }

    @Override
    public List<Map<String, Object>> getUserSimpleListByIdentity(String identity) {
        // 参数校验（根据业务需求）
        if (StringUtils.isEmpty(identity)) {
            throw new IllegalArgumentException("身份标识不能为空");
        }

        return userMapper.selectUserSimpleList(identity);
    }


    /**
     * 用户授权角色
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertUserAuth(Long userId, List<Long> roleIds) {
        userRoleMapper.deleteUserRoleByUserId(userId);
        insertUserRole(userId, roleIds);
    }

    /**
     * 修改用户状态
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserStatus(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户基本信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserProfile(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户头像
     *
     * @param userName 用户名
     * @param avatar   头像地址
     * @return 结果
     */
    @Override
    public boolean updateUserAvatar(String userName, String avatar) {
        return userMapper.updateUserAvatar(userName, avatar) > 0;
    }

    /**
     * 重置用户密码
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int resetPwd(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 重置用户密码
     *
     * @param userName 用户名
     * @param password 密码
     * @return 结果
     */
    @Override
    public int resetUserPwd(String userName, String password) {
        return userMapper.resetUserPwd(userName, password);
    }

    /**
     * 新增用户角色信息
     *
     * @param user 用户对象
     */
    public void insertUserRole(SysUser user) {
        this.insertUserRole(user.getUserId(), user.getRoleIds());
    }

    /**
     * 新增用户岗位信息
     *
     * @param user 用户对象
     */
    public void insertUserPost(SysUser user) {
        List<Long> posts = user.getPostIds();
        if (StringUtils.isNotEmpty(posts)) {
            // 新增用户与岗位管理
            List<SysUserPost> list = new ArrayList<SysUserPost>();
            for (Long postId : posts) {
                SysUserPost up = new SysUserPost();
                up.setUserId(user.getUserId());
                up.setPostId(postId);
                list.add(up);
            }
            int count = userPostMapper.batchUserPost(list);
            if (1 > count) {
                throw new ServiceException("数据操作失败");
            }
        }
    }

    /**
     * 新增用户角色信息
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    public void insertUserRole(Long userId, List<Long> roleIds) {
        if (StringUtils.isNotEmpty(roleIds)) {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>();
            for (Long roleId : roleIds) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            int count = userRoleMapper.batchUserRole(list);
            if (1 > count) {
                throw new ServiceException("数据操作失败");
            }
        }
    }

    /**
     * 通过用户ID删除用户
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteUserById(Long userId) {
        // 删除用户与角色关联
        int count = userRoleMapper.deleteUserRoleByUserId(userId);
        if (1 > count) {
            throw new ServiceException("数据操作失败");
        }
        // 删除用户与岗位表
        count = userPostMapper.deleteUserPostByUserId(userId);
        if (1 > count) {
            throw new ServiceException("数据操作失败");
        }
        count = userMapper.deleteUserById(userId);
        if (1 > count) {
            throw new ServiceException("数据操作失败");
        }
        return 1;
    }

    /**
     * 批量删除用户信息
     *
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteUserByIds(Long[] userIds) {
        for (Long userId : userIds) {
            checkUserAllowed(new SysUser(userId));
            checkUserDataScope(userId);
        }
        // 删除用户与角色关联
        userRoleMapper.deleteUserRole(userIds);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPost(userIds);
        return userMapper.deleteUserByIds(userIds);
    }

    /**
     * 导入用户数据
     *
     * @param userList        用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    @Override
    public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(userList) || userList.size() == 0) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (SysUser user : userList) {
            try {
                // 验证是否存在这个用户
                SysUser u = userMapper.selectUserByUserName(user.getUserName());
                if (StringUtils.isNull(u)) {
                    BeanValidators.validateWithException(validator, user);
                    user.setPassword(SecurityUtils.encryptPassword(password));
                    user.setCreateBy(operName);
                    userMapper.insertUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
                } else if (isUpdateSupport) {
                    BeanValidators.validateWithException(validator, user);
                    checkUserAllowed(u);
                    checkUserDataScope(u.getUserId());
                    user.setUserId(u.getUserId());
                    user.setUpdateBy(operName);
                    userMapper.updateUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public int chooseIdentity(String phone, String identity) {
        return userMapper.chooseIdentity(phone, identity);
    }

    @Override
    public List<SysUser> queryUserAndRole(UserDto user) {

        user.setCreateUser(SecurityUtils.getUsername());
        List<SysUser> users = userMapper.queryUserAndRole(user);

        return users;
    }


}
